package com.ics.cmsadmin.frame.core.bean;

import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import lombok.Data;

import java.util.Collection;
import java.util.Map;

/**
 * Created by Sandwich on 2018-07-14
 */
@Data
public class ApiResponse {
    private int code;
    private String message;
    private Object data;
    private int count;
    private boolean success;

    public ApiResponse(Object object){
        setMessage("");
        setCount(0);
        setCode(ApiResultEnum.SUCCESS.getCode());
        setData(null);
        if (object == null){
            return;
        }else if (object instanceof String){
            setMessage(object.toString());
            setCode(ApiResultEnum.FAILURE.getCode());
        }else if(object instanceof Boolean){
            setCode((Boolean) object == true ? ApiResultEnum.SUCCESS.getCode() : ApiResultEnum.FAILURE.getCode());
        }else if(object instanceof Collection){
            setData(object);
            setCount(((Collection) object).size());
        }else if(object instanceof Map){
            setData(object);
            setCount(((Map) object).size());
        }else if(object instanceof PageResult){
            PageResult pageResult = (PageResult) object;
            setData(pageResult.getDataList());
            setCount((int) pageResult.getTotalCount());
        }else if(object instanceof ApiResultEnum) {
            ApiResultEnum apiResultEnum = (ApiResultEnum) object;
            setMessage(apiResultEnum.getDetail());
            setCode(apiResultEnum.getCode());
        }else if(object instanceof CmsException){
            CmsException e = (CmsException) object;
            ApiResultEnum apiResultEnum = e.getApiResultEnum();
            setMessage(e.getMessage());
            setCode(apiResultEnum.getCode());
        }else if(object instanceof Throwable){
            setMessage("服务器异常");
            setCode(ApiResultEnum.FAILURE.getCode());
        }else{
            setData(object);
            setCount(1);
        }
        setSuccess(getCode() == ApiResultEnum.SUCCESS.getCode());
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public ApiResponse(ApiResultEnum rType, String message) {
        this.code = rType.getCode();
        this.message = rType.getDetail() + ":" + message;
    }

    public static ApiResponse getDefaultResponse() {
        return new ApiResponse(ApiResultEnum.SUCCESS);
    }

    public static ApiResponse getDefaultResponse(Object data) {
        return new ApiResponse(data);
    }

    public static ApiResponse getResponse(ApiResultEnum result) {
        return new ApiResponse(result);
    }
}
